package xiaojian.toolkit.netty.handler.codec.http.reactor;

import io.netty.handler.codec.http.FullHttpRequest;

import org.apache.commons.collections4.Closure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.netty.handler.codec.http.transformer.HttpRequestTransformer;

public class DecodeToBeanReactor implements HttpReactor {

	private static final Logger logger = LoggerFactory
			.getLogger(DecodeToBeanReactor.class);

	private HttpRequestTransformer reqTransformer;
	private Closure beanClosure;
	private HttpErrorReactor errorHandler;

	public Closure getBeanClosure() {
		return beanClosure;
	}

	public void setBeanClosure(Closure beanClosure) {
		this.beanClosure = beanClosure;
	}

	public HttpErrorReactor getErrorHandler() {
		return errorHandler;
	}

	public void setErrorHandler(HttpErrorReactor errorHandler) {
		this.errorHandler = errorHandler;
	}

	public HttpRequestTransformer getReqTransformer() {
		return reqTransformer;
	}

	public void setReqTransformer(HttpRequestTransformer reqTransformer) {
		this.reqTransformer = reqTransformer;
	}

	@Override
	public void onHttpRequest(FullHttpRequest request) {
		Object bean = null;

		try {
			bean = reqTransformer.transform(request);
		} catch (Exception e) {
			logger.error("req transform to bean:", e);
			if (null != errorHandler) {
				errorHandler.onError(request, e);
			} else {
				logger.warn("Can not transform bean for req [" + request
						+ "], and missing errorHandler.");
			}
		}

		if (null != bean && null != beanClosure) {
			beanClosure.execute(bean);
		}
	}
}
